using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace CloudApiServer.Services;
/// <summary>
/// 冲正服务
/// </summary>
public class FsiReverseService
{ 
        /// <summary>
        /// 2601冲正服务
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="CountrollerName">来源控制器名称</param>
        /// <returns>出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> RevsMethod(FsiRequestHeader<InputRevsMethod> fsiRequest, string CountrollerName)
        {
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            string fixmedins_code = fsiRequest.fixmedins_code;
            string psn_no = fsiRequest.Input.data.psn_no;
            string omsgid = fsiRequest.Input.data.omsgid;
            string oinfno = fsiRequest.Input.data.oinfno.Substring(0,4);
            if (string.IsNullOrEmpty(fixmedins_code)|| string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(omsgid) || string.IsNullOrEmpty(oinfno))
            {
                throw new Exception("参数校验失败：传入的机构编码|结算id|人员编号|就诊ID为空，请检查入参！");
            }
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            if (oinfno.Substring(0, 4)=="2102"|| oinfno.Substring(0, 4)=="2103")
            {
                string query = "select * from fsi_drugstore_order where order_canceltype =0 and LEFT(infno, 4)=@infno and psn_no=@psn_no and msgid=@msgid";
                var parameter = new List<MySqlParameter>
                {
                    new MySqlParameter("@infno", oinfno),
                    new MySqlParameter("@psn_no",psn_no),
                    new MySqlParameter("@msgid",omsgid)
                };
                DataTable dt  = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                if (dt.Rows.Count != 1)
                {
                    throw new Exception($"查询未冲正的结算记录失败！根据传入的原发送方报文ID【{omsgid}】接口编号【{oinfno}】人员编号【{psn_no}】查询到的总数为：{dt.Rows.Count}，不符合预设的要求！");
                }
                query = "update fsi_drugstore_order set order_canceltype = 1  and infno=@infno and psn_no=@psn_no and msgid=@msgid";
                await MySqlHelper.ExecuteNonQueryAsync(connectionString, query, parameter);
            }
            return true;
        }
}